﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebSOAPUI.Lib
{
    public class DefaultDateTimeConverter : Newtonsoft.Json.Converters.DateTimeConverterBase
    {
        public string Format { get; set; }
        public DefaultDateTimeConverter(string format)
        {
            this.Format = format;
        }

        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = reader.Value.ToString();
            var dt = DateTime.Now;
            if (!DateTime.TryParse(value, out dt))
            {
                dt = (DateTime)existingValue;
            }
            return dt;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DateTime dt = (DateTime)value;
            var fmt = this.Format ?? "yyyy-MM-dd";
            var str = dt.ToString(fmt);
            writer.WriteValue(str);
        }
    }
}